package leetcode.listnode;

import leetcode.ListNode;
import leetcode.ListNodeUtil;

/**
 * @author Cheng Jun
 * Description: 给你链表的头节点 head ，每 k 个节点一组进行翻转，请你返回修改后的链表。
 * <p>
 * k 是一个正整数，它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍，那么请将最后剩余的节点保持原有顺序。
 * <p>
 * 你不能只是单纯的改变节点内部的值，而是需要实际进行节点交换。
 * <p>
 * 链表中的节点数目为 n
 * 1 <= k <= n <= 5000
 * 0 <= Node.val <= 1000
 * 链接：https://leetcode.cn/problems/reverse-nodes-in-k-group
 * @version 1.0
 * @date 2022/8/6 20:26
 * 字节面试题
 */
public class reverseKGroup {

    public static void main(String[] args) {
        reverseKGroup1(ListNodeUtil.getListNode(new int[]{1, 2, 3, 4, 5}), 2);
    }

    /**
     * 思路：算出链表长度，然后计算出需要反转周期 turns = length / k;
     *
     * @param head
     * @param k
     * @return leetcode.ListNode
     * @author Cheng Jun
     * @date 2022/8/6 20:28
     */
    private static ListNode reverseKGroup(ListNode head, int k) {
        ListNode pointer = head;
        int length = 0;
        while (pointer != null) {
            length++;
            pointer = pointer.next;
        }
        int turns = length / k;
        ListNode[] groupArr = new ListNode[turns];
        int loop = 1;
        while (loop <= turns) {
            ListNode curNode = null;
            int count = 1;
            while (count <= k) {
                curNode = new ListNode(head.val, curNode);
                count++;
                head = head.next;
            }
            groupArr[loop - 1] = curNode;
            loop++;
        }
        for (int i = 0; i < turns; i++) {
            ListNode curNode = groupArr[i];
            while (curNode.next != null) {
                curNode = curNode.next;
            }
            if (i == (turns - 1)) {
                curNode.next = head;
            } else {
                curNode.next = groupArr[i + 1];
            }
        }
        return groupArr[0];
    }

    private static ListNode reverseKGroup1(ListNode head, int k) {
        ListNode hair = new ListNode(0, head);
        ListNode pre = hair;
        while (head != null) {
            ListNode tail = pre;
            // 查看剩余部分长度是否大于等于 k
            for (int i = 0; i < k; ++i) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            ListNode nex = tail.next;
            ListNode[] reverse = myReverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            // 把子链表重新接回原链表
            pre.next = head;
            tail.next = nex;
            pre = tail;
            head = tail.next;
        }

        return hair.next;
    }

    private static ListNode[] myReverse(ListNode head, ListNode tail) {
        ListNode prev = tail.next;
        ListNode p = head;
        while (prev != tail) {
            ListNode nex = p.next;
            p.next = prev;
            prev = p;
            p = nex;
        }
        return new ListNode[]{tail, head};
    }

}
